﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NCmd;

/// <summary>
/// 消息分发器
/// </summary>
public class Dispatcher
{
    /// <summary>
    /// 所有已注册的消息
    /// </summary>
    Dictionary<Type, Action<Cmd>> AllCmd = new Dictionary<Type, Action<Cmd>>();

    /// <summary>
    /// 被阻塞的消息
    /// </summary>
    List<Cmd> pausedCmdList = new List<Cmd>();

    public bool PauseCmdState;

    public void Dispatch(Cmd cmd = null)
    {
        if (cmd != null)
        {
            pausedCmdList.Add(cmd);
        }
        if (PauseCmdState) // 阻塞模式
        {
            return;
        }

        // 由于是模拟服务器，所以会存在消息套消息的情况，导致消息重复解析。所以这里暂存一下
        var tmpList = new List<Cmd>( pausedCmdList);
        pausedCmdList.Clear();
        foreach (var pCmd in tmpList)
        {
            dispatchOne(pCmd);
        }
    }

    void dispatchOne(Cmd cmd)
    {
        Action<Cmd> callback;
        if (AllCmd.TryGetValue(cmd.GetType(), out callback))
        {
            callback.Invoke(cmd);
        }
    }

    public void RegistCmd(Type cmdType, Action<Cmd> callback)
    {
        AllCmd[cmdType] = callback;
    }
}
